<!DOCTYPE html><html lang="zh-CN" data-theme="dark"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Koa2 | 北城韩雨</title><meta name="keywords" content="Node"><meta name="author" content="北城韩雨"><meta name="copyright" content="北城韩雨"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#0d0d0d"><meta name="description" content="Node">
<meta property="og:type" content="article">
<meta property="og:title" content="Koa2">
<meta property="og:url" content="http://example.com/2019/03/25/koa/index.html">
<meta property="og:site_name" content="北城韩雨">
<meta property="og:description" content="Node">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.vjshi.com%2F2018-07-17%2F3eca5394963b50e37b7be2ba320029ec%2F00003.jpg%3Fx-oss-process%3Dstyle%2Fwatermark&refer=http%3A%2F%2Fpic.vjshi.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1629530644&t=10679b5732c52e39eeb588040240a790">
<meta property="article:published_time" content="2019-03-24T16:00:00.000Z">
<meta property="article:modified_time" content="2019-06-02T16:00:00.000Z">
<meta property="article:author" content="北城韩雨">
<meta property="article:tag" content="Koa2">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.vjshi.com%2F2018-07-17%2F3eca5394963b50e37b7be2ba320029ec%2F00003.jpg%3Fx-oss-process%3Dstyle%2Fwatermark&refer=http%3A%2F%2Fpic.vjshi.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1629530644&t=10679b5732c52e39eeb588040240a790"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="http://example.com/2019/03/25/koa/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'mediumZoom',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Koa2',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2019-06-03 00:00:00'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/css/custom.css"  media="defer" onload="this.media='all'"><link rel="stylesheet" href="/css/coin.css"  media="defer" onload="this.media='all'"><link rel="stylesheet" href="/css/liuxing.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/l-lin/font-awesome-animation/dist/font-awesome-animation.min.css"  media="defer" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper/swiper-bundle.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/zhheo/JS-Heo@main/bb/showbb_in_index.css"><!-- hexo injector head_end start --><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" media="print" onload="this.media='screen'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/l-lin/font-awesome-animation/dist/font-awesome-animation.min.css" media="defer" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hexo-butterfly-tag-plugins-plus/lib/tag_plugins.min.css" media="defer" onload="this.media='all'"><!-- hexo injector head_end end --><meta name="generator" content="Hexo 5.3.0"></head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/my.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">65</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">23</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">21</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/"><i class="fa-fw fas fa-home faa-tada"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/shuoshuo/"><i class="fa-fw fas fa-archive faa-tada"></i><span> 叨逼叨</span></a></div><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/tags/"><i class="fa-fw fas fa-tags faa-tada"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/categories/"><i class="fa-fw fas fa-folder-open faa-tada"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/link/"><i class="fa-fw fas fa-link faa-tada"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/comments/"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-message"></use></svg><span> 留言板</span></a></div><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/about/"><i class="fa-fw fas fa-heart faa-tada"></i><span> 个人简介</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.vjshi.com%2F2018-07-17%2F3eca5394963b50e37b7be2ba320029ec%2F00003.jpg%3Fx-oss-process%3Dstyle%2Fwatermark&amp;refer=http%3A%2F%2Fpic.vjshi.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1629530644&amp;t=10679b5732c52e39eeb588040240a790')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">北城韩雨</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/"><i class="fa-fw fas fa-home faa-tada"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/shuoshuo/"><i class="fa-fw fas fa-archive faa-tada"></i><span> 叨逼叨</span></a></div><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/tags/"><i class="fa-fw fas fa-tags faa-tada"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/categories/"><i class="fa-fw fas fa-folder-open faa-tada"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/link/"><i class="fa-fw fas fa-link faa-tada"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/comments/"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-message"></use></svg><span> 留言板</span></a></div><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/about/"><i class="fa-fw fas fa-heart faa-tada"></i><span> 个人简介</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Koa2</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2019-03-24T16:00:00.000Z" title="发表于 2019-03-25 00:00:00">2019-03-25</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2019-06-02T16:00:00.000Z" title="更新于 2019-06-03 00:00:00">2019-06-03</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Node/">Node</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">3k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>13分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Koa2"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="koa正常流程"><a href="#koa正常流程" class="headerlink" title="koa正常流程"></a>koa正常流程</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">1.安装 koa</span><br><span class="line">2.创建服务</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">index.js -&gt; 创建服务代码</span><br><span class="line"><span class="keyword">const</span> Koa =  <span class="built_in">require</span>(<span class="string">&#x27;koa&#x27;</span>)</span><br><span class="line"><span class="keyword">const</span> app = <span class="keyword">new</span> Koa()</span><br><span class="line">app.use(<span class="function">(<span class="params">ctx,next</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">//这里就返回了数据</span></span><br><span class="line">    ctx.body =[ &#123;</span><br><span class="line">        name:<span class="string">&#x27;koa&#x27;</span></span><br><span class="line">    &#125;]</span><br><span class="line">&#125;)</span><br><span class="line">app.listen(<span class="number">3000</span>)</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> Koa =  <span class="built_in">require</span>(<span class="string">&#x27;koa&#x27;</span>)</span><br><span class="line"><span class="keyword">const</span> app = <span class="keyword">new</span> Koa()</span><br><span class="line">app.use(<span class="function">(<span class="params">ctx,next</span>) =&gt;</span> &#123;</span><br><span class="line">    ctx.body =[ &#123;</span><br><span class="line">        name:<span class="string">&#x27;koa&#x27;</span></span><br><span class="line">    &#125;]</span><br><span class="line">    <span class="comment">//这里切记要加next() 否则我们下面的无法访问</span></span><br><span class="line">    next()</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">app.use(<span class="function">(<span class="params">ctx,next</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span>(ctx.url === <span class="string">&#x27;/html&#x27;</span>)&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;url&#x27;</span> + ctx.url) <span class="comment">//这里就是你前端请求的地址</span></span><br><span class="line">        ctx.type = <span class="string">&#x27;text/html;charset=utf-8&#x27;</span> <span class="comment">//这里就是请求的头</span></span><br><span class="line">        ctx.body = <span class="string">`&lt;p&gt;我的名字是<span class="subst">$&#123;ctx.body[<span class="number">0</span>].name&#125;</span>&lt;/p&gt;`</span> <span class="comment">//这里就是返回的数据</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line">app.listen(<span class="number">3000</span>)</span><br></pre></td></tr></table></figure>
<h2 id="上传文件"><a href="#上传文件" class="headerlink" title="上传文件"></a>上传文件</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span>我们前端再长传文件的时候 用input框 type=flie类型即可 然后可以通过DOM拿到这个选择框的值 直接发送给后台就好</span><br></pre></td></tr></table></figure>
<h2 id="后端接收文件-三种方式"><a href="#后端接收文件-三种方式" class="headerlink" title="后端接收文件 三种方式"></a>后端接收文件 三种方式</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span>采用流的形式 就好比管道 你那边供水 我这边指定一个地方 我们所写的后台代码就是搭接管道</span><br><span class="line"><span class="number">2.</span>采用buffer 的方式 就是我们把前端传过来的转换成二进制数据 然后再把他写再我们指定的文件里</span><br><span class="line"><span class="number">3.</span>采用流写入 有点像第一钟和第三种相互结合的方式</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//流</span></span><br><span class="line"> <span class="keyword">if</span> (pathname === <span class="string">&#x27;/upload&#x27;</span>) &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;upload....&#x27;</span>)</span><br><span class="line">        <span class="keyword">const</span> fileName = request.headers[<span class="string">&#x27;file-name&#x27;</span>] ? request.headers[<span class="string">&#x27;file-name&#x27;</span>] : <span class="string">&#x27;abc.png&#x27;</span></span><br><span class="line">        <span class="comment">//写好要存入的路径</span></span><br><span class="line">        <span class="keyword">const</span> outputFile = path.resolve(__dirname, fileName)</span><br><span class="line">        <span class="comment">//开始搭管道 管道的一头是你是服务器的这段最终的路径</span></span><br><span class="line">        <span class="keyword">const</span> fis = fs.createWriteStream(outputFile)</span><br><span class="line">        <span class="comment">//然后你的管道开始链接</span></span><br><span class="line">        request.pipe(fis)</span><br><span class="line">        response.end()</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//转换二进制数据</span></span><br><span class="line"><span class="keyword">const</span> chunk = []</span><br><span class="line"><span class="comment">//开始接受你前端传过来的数据 </span></span><br><span class="line">request.on(<span class="string">&#x27;data&#x27;</span>,<span class="function"><span class="params">data</span> =&gt;</span> &#123;</span><br><span class="line">    chunk.push(data)</span><br><span class="line">    size += data.length</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;data:&#x27;</span>,data ,size)</span><br><span class="line">&#125;)</span><br><span class="line">request.on(<span class="string">&#x27;end&#x27;</span>,<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;end...&#x27;</span>)</span><br><span class="line">    <span class="comment">//然后转换成二进制数据</span></span><br><span class="line">    <span class="keyword">const</span> buffer = Buffer.concat(chunk,size)</span><br><span class="line">    size = <span class="number">0</span></span><br><span class="line">    <span class="comment">//然后把他写再一个文件里</span></span><br><span class="line">    fs.writeFileSync(outputFile,buffer)</span><br><span class="line">    response.end()</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//流写入</span></span><br><span class="line"> request.on(<span class="string">&#x27;data&#x27;</span>, <span class="function"><span class="params">data</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;data:&#x27;</span>,data)</span><br><span class="line">    fis.write(data)</span><br><span class="line">&#125;)</span><br><span class="line">request.on(<span class="string">&#x27;end&#x27;</span>, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">    fis.end()</span><br><span class="line">    response.end()</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h2 id="koa-router的配置"><a href="#koa-router的配置" class="headerlink" title="koa-router的配置"></a>koa-router的配置</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span>这里我们还是采取分层办法 MVC 路由作为我们C层</span><br><span class="line"><span class="number">2.</span>这里配置路由是通过koa-router去配置的 所以要安装</span><br><span class="line"><span class="number">3.</span>然后在启动文件里 引入 和注册</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//首先我们分层 在controller的 文件夹下新建一个user.js 文件  这里存放所有跟用户相关的接口</span></span><br><span class="line"><span class="keyword">const</span> Router = <span class="built_in">require</span>(<span class="string">&#x27;koa-router&#x27;</span>)</span><br><span class="line"><span class="keyword">const</span> router = <span class="keyword">new</span> Router()</span><br><span class="line">router.get(<span class="string">&#x27;/index&#x27;</span>,<span class="keyword">async</span> (ctx) =&gt; &#123;</span><br><span class="line">    ctx.body=<span class="string">&#x27;hellow index&#x27;</span></span><br><span class="line">&#125;)</span><br><span class="line">router.get(<span class="string">&#x27;/&#x27;</span>,<span class="keyword">async</span> (ctx) =&gt; &#123;</span><br><span class="line">    ctx.body=<span class="string">&#x27;user&#x27;</span></span><br><span class="line">&#125;)</span><br><span class="line"><span class="built_in">module</span>.exports = router</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//然后在启动文件里注册 和引入</span></span><br><span class="line"><span class="keyword">const</span> Router = <span class="built_in">require</span>(<span class="string">&#x27;koa-router&#x27;</span>)</span><br><span class="line"><span class="comment">//这就是帮我们上面的建设的那些用户某块的接口</span></span><br><span class="line"><span class="keyword">const</span> user = <span class="built_in">require</span>(<span class="string">&#x27;./controller/user.js&#x27;</span>)</span><br><span class="line"><span class="keyword">const</span> home = <span class="built_in">require</span>(<span class="string">&#x27;./controller/home.js&#x27;</span>)</span><br><span class="line"><span class="keyword">const</span> router = <span class="keyword">new</span> Router()</span><br><span class="line"><span class="comment">//然后注册一下 就可以使用了 这里的路径是二级路径 /user对应的是我们上面的接口的&#x27;/&#x27;</span></span><br><span class="line">router.use(<span class="string">&#x27;/user&#x27;</span>,user.routes())</span><br><span class="line"><span class="comment">//如果还有其他模块 就继续如下处理</span></span><br><span class="line">router.use(<span class="string">&#x27;/home&#x27;</span>,home.routes())</span><br><span class="line"><span class="comment">//加载路由中间件</span></span><br><span class="line">app.use(router.routes())</span><br><span class="line"><span class="comment">//和所有的方法</span></span><br><span class="line">app.use(router.allowedMethods())</span><br></pre></td></tr></table></figure>
<h2 id="koa-bodyParser"><a href="#koa-bodyParser" class="headerlink" title="koa-bodyParser"></a>koa-bodyParser</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span>用来接收post请求 安装koa-bodyParser包</span><br><span class="line"><span class="number">2.</span>然后在启动文件里注册</span><br><span class="line"><span class="keyword">const</span> bodyParser = <span class="built_in">require</span>(<span class="string">&#x27;koa-bodyParser&#x27;</span>)</span><br><span class="line">app.use(bodyParser())</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//参数的接收在ctx.request.body里接收</span></span><br><span class="line">router.post(<span class="string">&#x27;/index&#x27;</span>,<span class="keyword">async</span> (ctx) =&gt; &#123;</span><br><span class="line">    <span class="comment">//前端传过来的参数</span></span><br><span class="line">    ctx.request.body</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h2 id="设置跨域-cors"><a href="#设置跨域-cors" class="headerlink" title="设置跨域 cors"></a>设置跨域 cors</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span>这里设置了头 支持所有的前端去请求</span><br><span class="line"><span class="number">2.</span>使用koa2-cors安装包</span><br><span class="line"><span class="number">3.</span>然后注册一下</span><br><span class="line"><span class="number">3.</span>在启动文件里写下面这些</span><br><span class="line"><span class="keyword">const</span> cors = <span class="built_in">require</span>(<span class="string">&#x27;koa2-cors&#x27;</span>)</span><br><span class="line">app.use(cors())</span><br></pre></td></tr></table></figure>
<h2 id="mongoose链接"><a href="#mongoose链接" class="headerlink" title="mongoose链接"></a>mongoose链接</h2><h3 id="1-建立链接"><a href="#1-建立链接" class="headerlink" title="1.建立链接"></a>1.建立链接</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//链接</span></span><br><span class="line"><span class="keyword">const</span> mongoose = <span class="built_in">require</span>(<span class="string">&#x27;mongoose&#x27;</span>)</span><br><span class="line"><span class="keyword">const</span> db = <span class="string">&quot;mongodb://localhost/smile-vue&quot;</span></span><br><span class="line"><span class="keyword">const</span> glob = <span class="built_in">require</span>(<span class="string">&#x27;glob&#x27;</span>)</span><br><span class="line"><span class="keyword">const</span> &#123;resolve&#125; = <span class="built_in">require</span>(<span class="string">&#x27;path&#x27;</span>)</span><br><span class="line"><span class="comment">//这里就是读取了我们的数据模型schema</span></span><br><span class="line"><span class="built_in">exports</span>.initSchemas = <span class="function">()=&gt;</span>&#123;</span><br><span class="line">    glob.sync(resolve(__dirname,<span class="string">&#x27;./schema&#x27;</span>,<span class="string">&#x27;**/*.js&#x27;</span>)).forEach(<span class="built_in">require</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="built_in">exports</span>.connect = <span class="function">()=&gt;</span>&#123;</span><br><span class="line">    <span class="comment">//连接数据库</span></span><br><span class="line">    mongoose.connect(db)</span><br><span class="line">    <span class="keyword">let</span>  maxConnectTimes = <span class="number">0</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve,reject</span>)=&gt;</span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//增加数据库监听事件</span></span><br><span class="line">        mongoose.connection.on(<span class="string">&#x27;disconnected&#x27;</span>,<span class="function">()=&gt;</span>&#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&#x27;***********数据库断开***********&#x27;</span>)</span><br><span class="line">            <span class="keyword">if</span>(maxConnectTimes&lt;=<span class="number">3</span>)&#123;</span><br><span class="line">                maxConnectTimes++</span><br><span class="line">                mongoose.connect(db)</span><br><span class="line">            &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">                reject()</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">&#x27;数据库出现问题，程序无法搞定，请人为修理.....&#x27;</span>)</span><br><span class="line">            &#125;</span><br><span class="line">           </span><br><span class="line">        &#125;)</span><br><span class="line"></span><br><span class="line">        mongoose.connection.on(<span class="string">&#x27;error&#x27;</span>,<span class="function">(<span class="params">err</span>)=&gt;</span>&#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&#x27;***********数据库错误&#x27;</span>)</span><br><span class="line">            <span class="keyword">if</span>(maxConnectTimes&lt;=<span class="number">3</span>)&#123;</span><br><span class="line">                maxConnectTimes++</span><br><span class="line">                mongoose.connect(db)</span><br><span class="line">            &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">                reject(err)</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">&#x27;数据库出现问题，程序无法搞定，请人为修理.....&#x27;</span>)</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;)</span><br><span class="line">        <span class="comment">//链接打开的时</span></span><br><span class="line">        mongoose.connection.once(<span class="string">&#x27;open&#x27;</span>,<span class="function">()=&gt;</span>&#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&#x27;MongoDB connected successfully&#x27;</span>)   </span><br><span class="line">             resolve()</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="2-调用链接"><a href="#2-调用链接" class="headerlink" title="2.调用链接"></a>2.调用链接</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//在我们的index.js文件里即可 也就是启动文件</span></span><br><span class="line"><span class="comment">//调用 使用我们的用函数  然后 让数据库链接成功</span></span><br><span class="line"><span class="keyword">const</span> Koa = <span class="built_in">require</span>(<span class="string">&#x27;koa&#x27;</span>)</span><br><span class="line"><span class="keyword">const</span> app = <span class="keyword">new</span> Koa()</span><br><span class="line"><span class="keyword">const</span> mongoose = <span class="built_in">require</span>(<span class="string">&#x27;mongoose&#x27;</span>)</span><br><span class="line"><span class="comment">//引入connect</span></span><br><span class="line"><span class="keyword">const</span> &#123;connect,initSchemas&#125; = <span class="built_in">require</span>(<span class="string">&#x27;./model/init.js&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">//立即执行函数</span></span><br><span class="line">;(<span class="keyword">async</span> () =&gt;&#123;</span><br><span class="line">    <span class="comment">//启动链接</span></span><br><span class="line">    <span class="keyword">await</span> connect()</span><br><span class="line">    <span class="comment">//读取数据模型文件</span></span><br><span class="line">    initSchemas()</span><br><span class="line">    <span class="comment">//随便插入一下文件实验一下</span></span><br><span class="line">    <span class="keyword">let</span> User = mongoose.model(<span class="string">&#x27;User&#x27;</span>)</span><br><span class="line">    <span class="built_in">console</span>.log(User,<span class="string">&#x27;-----user&#x27;</span>)</span><br><span class="line">    <span class="keyword">let</span> oneUser = <span class="keyword">new</span> User(&#123;<span class="attr">userName</span>:<span class="string">&#x27;wangzheng&#x27;</span>,<span class="attr">password</span>:<span class="string">&#x27;123456&#x27;</span>&#125;)</span><br><span class="line">    oneUser.save().then(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;插入成功&#x27;</span>)</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;)()</span><br></pre></td></tr></table></figure>
<h3 id="3-密码的加密处理"><a href="#3-密码的加密处理" class="headerlink" title="3.密码的加密处理"></a>3.密码的加密处理</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span>这里我们采用了bcrypt包 也就哈希的一种 先去加盐</span><br><span class="line"><span class="number">2.</span>上面的操作我们在数据模型里完成</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> mongoose = <span class="built_in">require</span>(<span class="string">&#x27;mongoose&#x27;</span>)</span><br><span class="line"><span class="keyword">const</span> Schema = mongoose.Schema</span><br><span class="line"><span class="keyword">let</span> ObjectId = Schema.Types.ObjectId</span><br><span class="line"><span class="keyword">const</span> bcrypt = <span class="built_in">require</span>(<span class="string">&#x27;bcrypt&#x27;</span>)</span><br><span class="line"><span class="comment">//这个是一种加字节的数量和长度</span></span><br><span class="line"><span class="keyword">const</span> SALT_WORK_FACTOR = <span class="number">10</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//创建UserShema</span></span><br><span class="line"><span class="keyword">const</span> userSchema = <span class="keyword">new</span> Schema(&#123;</span><br><span class="line">    UserId :&#123;<span class="attr">type</span>:ObjectId&#125;,</span><br><span class="line">    userName : &#123;<span class="attr">unique</span>:<span class="literal">true</span>,<span class="attr">type</span>:<span class="built_in">String</span>&#125;,</span><br><span class="line">    password : <span class="built_in">String</span>,</span><br><span class="line">    createAt:&#123;<span class="attr">type</span>:<span class="built_in">Date</span>, <span class="attr">default</span>:<span class="built_in">Date</span>.now()&#125;,</span><br><span class="line">    lastLoginAt:&#123;<span class="attr">type</span>:<span class="built_in">Date</span>, <span class="attr">default</span>:<span class="built_in">Date</span>.now()&#125;</span><br><span class="line">&#125;,&#123;</span><br><span class="line">  collection:<span class="string">&#x27;user&#x27;</span>  </span><br><span class="line">&#125;) </span><br><span class="line"><span class="comment">//这面就是加盐的处理了</span></span><br><span class="line">userSchema.pre(<span class="string">&#x27;save&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params">next</span>)</span>&#123;</span><br><span class="line">    bcrypt.genSalt(SALT_WORK_FACTOR,<span class="function">(<span class="params">err,salt</span>)=&gt;</span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(err) <span class="keyword">return</span> next(err)</span><br><span class="line">        bcrypt.hash(<span class="built_in">this</span>.password,salt,<span class="function">(<span class="params">err,hash</span>)=&gt;</span>&#123;</span><br><span class="line">            <span class="keyword">if</span>(err) <span class="keyword">return</span> next(err)</span><br><span class="line">            <span class="built_in">this</span>.password = hash</span><br><span class="line">            next()</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">//发布模型</span></span><br><span class="line">mongoose.model(<span class="string">&#x27;User&#x27;</span>,userSchema)</span><br></pre></td></tr></table></figure>
<h2 id="注册的代码"><a href="#注册的代码" class="headerlink" title="注册的代码"></a>注册的代码</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span>首先要确保你的数据库是链接的状态 和模型已经数据模型已经映射到了本地</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//确保已经链接 并已经把数据模型映射到文件本地 在index.js文件里 启动文件</span></span><br><span class="line"><span class="keyword">const</span> mongoose = <span class="built_in">require</span>(<span class="string">&#x27;mongoose&#x27;</span>)</span><br><span class="line"><span class="keyword">const</span> &#123;connect,initSchemas&#125; = <span class="built_in">require</span>(<span class="string">&#x27;./model/init.js&#x27;</span>)</span><br><span class="line"><span class="comment">// 立即执行函数</span></span><br><span class="line">;(<span class="keyword">async</span> () =&gt;&#123;</span><br><span class="line">    <span class="keyword">await</span> connect()</span><br><span class="line">    initSchemas()</span><br><span class="line">&#125;)()</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//当前端访问进口的时候 我们把前端传过来的参数 放进我们的新的User里 然后保存</span></span><br><span class="line"><span class="keyword">const</span> mongoose = <span class="built_in">require</span>(<span class="string">&#x27;mongoose&#x27;</span>)</span><br><span class="line">router.post(<span class="string">&#x27;/&#x27;</span>,<span class="keyword">async</span> (ctx) =&gt; &#123;</span><br><span class="line">    <span class="comment">//导入User数据模型</span></span><br><span class="line">    <span class="keyword">const</span> User = mongoose.model(<span class="string">&#x27;User&#x27;</span>)</span><br><span class="line">    <span class="comment">//然后  把前端传过来的 新创建 一个用户信息</span></span><br><span class="line">    <span class="keyword">let</span> newUser = <span class="keyword">new</span> User(ctx.request.body)</span><br><span class="line">    <span class="comment">//然后保存 如果成功 就返回给前端的状态</span></span><br><span class="line">    <span class="keyword">await</span> newUser.save().then(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        ctx.body = &#123;</span><br><span class="line">            code:<span class="number">200</span>,</span><br><span class="line">            message:<span class="string">&#x27;注册成功&#x27;</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="built_in">module</span>.exports = router</span><br></pre></td></tr></table></figure>
<h2 id="登录"><a href="#登录" class="headerlink" title="登录"></a>登录</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span>首先我们要先去查用户名 </span><br><span class="line"><span class="number">2.</span>如果用户名查到 再去查密码</span><br><span class="line"><span class="number">3.</span>密码这里我们前期是经过  <span class="keyword">const</span> bcrypt = <span class="built_in">require</span>(<span class="string">&#x27;bcrypt&#x27;</span>) 这个包处理过的</span><br><span class="line"><span class="number">4.</span>所以 密码需要比对 和解密 这里我们直接卸载数据模型里</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//数据模型的方法</span></span><br><span class="line"><span class="keyword">const</span> mongoose = <span class="built_in">require</span>(<span class="string">&#x27;mongoose&#x27;</span>)</span><br><span class="line"><span class="keyword">const</span> Schema = mongoose.Schema</span><br><span class="line"><span class="keyword">let</span> ObjectId = Schema.Types.ObjectId</span><br><span class="line"><span class="keyword">const</span> bcrypt = <span class="built_in">require</span>(<span class="string">&#x27;bcrypt&#x27;</span>)</span><br><span class="line"><span class="comment">//这个是一种加字节的数量和长度</span></span><br><span class="line"><span class="keyword">const</span> SALT_WORK_FACTOR = <span class="number">10</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//创建UserShema</span></span><br><span class="line"><span class="keyword">const</span> userSchema = <span class="keyword">new</span> Schema(&#123;</span><br><span class="line">    UserId :&#123;<span class="attr">type</span>:ObjectId&#125;,</span><br><span class="line">    userName : &#123;<span class="attr">unique</span>:<span class="literal">true</span>,<span class="attr">type</span>:<span class="built_in">String</span>&#125;,</span><br><span class="line">    password : <span class="built_in">String</span>,</span><br><span class="line">    createAt:&#123;<span class="attr">type</span>:<span class="built_in">Date</span>, <span class="attr">default</span>:<span class="built_in">Date</span>.now()&#125;,</span><br><span class="line">    lastLoginAt:&#123;<span class="attr">type</span>:<span class="built_in">Date</span>, <span class="attr">default</span>:<span class="built_in">Date</span>.now()&#125;</span><br><span class="line">&#125;,&#123;</span><br><span class="line">  collection:<span class="string">&#x27;user&#x27;</span>  </span><br><span class="line">&#125;) </span><br><span class="line"><span class="comment">//这面就是加盐的处理了</span></span><br><span class="line">userSchema.pre(<span class="string">&#x27;save&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params">next</span>)</span>&#123;</span><br><span class="line">    bcrypt.genSalt(SALT_WORK_FACTOR,<span class="function">(<span class="params">err,salt</span>)=&gt;</span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(err) <span class="keyword">return</span> next(err)</span><br><span class="line">        bcrypt.hash(<span class="built_in">this</span>.password,salt,<span class="function">(<span class="params">err,hash</span>)=&gt;</span>&#123;</span><br><span class="line">            <span class="keyword">if</span>(err) <span class="keyword">return</span> next(err)</span><br><span class="line">            <span class="built_in">this</span>.password = hash</span><br><span class="line">            next()</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">//比对密码的方法 在我们的数据模型中去完成 这里在我们登录接口的时候 就可以用</span></span><br><span class="line">userSchema.methods = &#123;</span><br><span class="line">    comparePassword:<span class="function">(<span class="params">_password,password</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve,reject</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="comment">//调用了bcrypt的方法 去比对密码 err是错误 isMatc是成功</span></span><br><span class="line">            bcrypt.compare(_password,password,<span class="function">(<span class="params">err,isMatc</span>) =&gt;</span> &#123;</span><br><span class="line">                <span class="comment">//如果没有错误 就返回成功</span></span><br><span class="line">                <span class="keyword">if</span>(!err) resolve(isMatc)</span><br><span class="line">                <span class="comment">//如果失败了 就返回错误</span></span><br><span class="line">                <span class="keyword">else</span> reject(err)</span><br><span class="line">            &#125;)</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//发布模型</span></span><br><span class="line">mongoose.model(<span class="string">&#x27;User&#x27;</span>,userSchema)</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//登录接口</span></span><br><span class="line">router.post(<span class="string">&#x27;/loging&#x27;</span>,<span class="function">(<span class="params">cxt</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">//把前端的用户和密码解构出来</span></span><br><span class="line">    <span class="keyword">let</span> userName = ctx.request.body.userName</span><br><span class="line">    <span class="keyword">let</span> password = ctx.request.body.password</span><br><span class="line">    <span class="comment">//映射我们的数据模型</span></span><br><span class="line">    <span class="keyword">const</span> User =  mongoose.model(<span class="string">&#x27;User&#x27;</span>)</span><br><span class="line">    <span class="comment">//去数去模型中查找先看看有没有用户名.exex就是找到了  然后 他返回的是用户和密码</span></span><br><span class="line">    <span class="keyword">await</span> User.findOne(&#123;<span class="attr">userName</span>:userName&#125;).exec().then( <span class="keyword">async</span> (res) =&gt; &#123;</span><br><span class="line">        <span class="comment">//如果找到了 我们新把数据模型实力化出来</span></span><br><span class="line">        <span class="keyword">if</span>(res)&#123;</span><br><span class="line">            <span class="keyword">let</span> newUser = <span class="keyword">new</span> User()</span><br><span class="line">            <span class="comment">//用我们自己写好的方法 去比对密码 这里因为上面我们已经封装了 所以就直接返回成功</span></span><br><span class="line">            <span class="keyword">await</span> newUser.comparePassword(pasword,res.password).then(isMatc)</span><br><span class="line">        &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">            <span class="comment">//如果找不到就提示用户名不存在</span></span><br><span class="line">            ctx.body = &#123;</span><br><span class="line">                code:<span class="number">200</span>,</span><br><span class="line">                message:<span class="string">&#x27;用户名不存在&#x27;</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;).catch( <span class="function"><span class="params">error</span> =&gt;</span> &#123;</span><br><span class="line">        ctx.body = &#123;</span><br><span class="line">            code:<span class="string">&#x27;500&#x27;</span>,</span><br><span class="line">            message:<span class="string">&#x27;服务器错误&#x27;</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="built_in">module</span>.exports = router</span><br></pre></td></tr></table></figure>
<h2 id="数据库文件的写入"><a href="#数据库文件的写入" class="headerlink" title="数据库文件的写入"></a>数据库文件的写入</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span>核心就是读文件 的功能 然后插入到数据库里去</span><br><span class="line"><span class="number">2.</span>首先你要准备一个<span class="built_in">JSON</span>文件 里面放你的数据</span><br><span class="line"><span class="number">3.</span>然后你的数据模型要和那个json文件的字段一样</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//这里我们用商品举例 下面是数据模型文件</span></span><br><span class="line"><span class="keyword">const</span> mongoose = <span class="built_in">require</span>(<span class="string">&#x27;mongoose&#x27;</span>)    <span class="comment">//引入Mongoose</span></span><br><span class="line"><span class="keyword">const</span> Schema = mongoose.Schema          <span class="comment">//声明Schema</span></span><br><span class="line"><span class="keyword">let</span> ObjectId = Schema.Types.ObjectId    <span class="comment">//声明Object类型</span></span><br><span class="line"><span class="comment">//这些字段都和你的json文件里的要一致</span></span><br><span class="line"><span class="keyword">const</span> goodsSchema = <span class="keyword">new</span> Schema(&#123;</span><br><span class="line">    ID:&#123;<span class="attr">unique</span>:<span class="literal">true</span>,<span class="attr">type</span>:<span class="built_in">String</span>&#125;,</span><br><span class="line">    GOODS_SERIAL_NUMBER:<span class="built_in">String</span>,</span><br><span class="line">    SHOP_ID:<span class="built_in">String</span>,</span><br><span class="line">    SUB_ID:<span class="built_in">String</span>,</span><br><span class="line">    GOOD_TYPE:<span class="built_in">Number</span>,</span><br><span class="line">    STATE:<span class="built_in">Number</span>,</span><br><span class="line">    NAME:<span class="built_in">String</span>,</span><br><span class="line">    ORI_PRICE:<span class="built_in">Number</span>,</span><br><span class="line">    PRESENT_PRICE:<span class="built_in">Number</span>,</span><br><span class="line">    AMOUNT:<span class="built_in">Number</span>,</span><br><span class="line">    DETAIL:<span class="built_in">String</span>,</span><br><span class="line">    BRIEF:<span class="built_in">String</span>,</span><br><span class="line">    SALES_COUNT:<span class="built_in">Number</span>,</span><br><span class="line">    IMAGE1:<span class="built_in">String</span>,</span><br><span class="line">    IMAGE2:<span class="built_in">String</span>,</span><br><span class="line">    IMAGE3:<span class="built_in">String</span>,</span><br><span class="line">    IMAGE4:<span class="built_in">String</span>,</span><br><span class="line">    IMAGE5:<span class="built_in">String</span>,</span><br><span class="line">    ORIGIN_PLACE:<span class="built_in">String</span>,</span><br><span class="line">    GOOD_SCENT:<span class="built_in">String</span>,</span><br><span class="line">    CREATE_TIME:<span class="built_in">String</span>,</span><br><span class="line">    UPDATE_TIME:<span class="built_in">String</span>,</span><br><span class="line">    IS_RECOMMEND:<span class="built_in">Number</span>,</span><br><span class="line">    PICTURE_COMPERSS_PATH:<span class="built_in">String</span></span><br><span class="line">&#125;,&#123;</span><br><span class="line">    collections:<span class="string">&#x27;Goods&#x27;</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">mongoose.model(<span class="string">&#x27;Goods&#x27;</span>,goodsSchema)</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//然后我们写新写的接口 appAPI文件夹下的good.js文件 </span></span><br><span class="line"><span class="keyword">const</span> Koa = <span class="built_in">require</span>(<span class="string">&#x27;koa&#x27;</span>)</span><br><span class="line"><span class="keyword">const</span> app = <span class="keyword">new</span> Koa()</span><br><span class="line"><span class="keyword">const</span> Router = <span class="built_in">require</span> (<span class="string">&#x27;koa-router&#x27;</span>)</span><br><span class="line"><span class="keyword">let</span> router = <span class="keyword">new</span> Router()</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> mongoose = <span class="built_in">require</span>(<span class="string">&#x27;mongoose&#x27;</span>)</span><br><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">//这里就是当有请求这个接口的时候</span></span><br><span class="line">router.get(<span class="string">&#x27;/insertAllGoodsInfo&#x27;</span>,<span class="keyword">async</span>(ctx)=&gt;&#123;</span><br><span class="line">	<span class="comment">//去读文件</span></span><br><span class="line">     fs.readFile(<span class="string">&#x27;./goods.json&#x27;</span>,<span class="string">&#x27;utf8&#x27;</span>,<span class="function">(<span class="params">err,data</span>)=&gt;</span>&#123;</span><br><span class="line">         <span class="comment">//转换JSON</span></span><br><span class="line">        data=<span class="built_in">JSON</span>.parse(data)</span><br><span class="line">        <span class="keyword">let</span> saveCount=<span class="number">0</span></span><br><span class="line">        <span class="comment">//映射数据模型</span></span><br><span class="line">        <span class="keyword">const</span> Goods = mongoose.model(<span class="string">&#x27;Goods&#x27;</span>)</span><br><span class="line">        <span class="comment">//循环我们读取的文件</span></span><br><span class="line">        data.map(<span class="function">(<span class="params">value,index</span>)=&gt;</span>&#123;</span><br><span class="line">            <span class="built_in">console</span>.log(value)</span><br><span class="line">            <span class="comment">//每次循环一次就创建一条数据 并把我们的数据模型插入进去</span></span><br><span class="line">            <span class="keyword">let</span> newGoods = <span class="keyword">new</span> Goods(value)</span><br><span class="line">            <span class="comment">//然后保存数据</span></span><br><span class="line">            newGoods.save().then(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">                saveCount++</span><br><span class="line">                <span class="built_in">console</span>.log(<span class="string">&#x27;成功&#x27;</span>+saveCount)</span><br><span class="line">            &#125;).catch(<span class="function"><span class="params">error</span>=&gt;</span>&#123;</span><br><span class="line">                 <span class="built_in">console</span>.log(<span class="string">&#x27;失败：&#x27;</span>+error)</span><br><span class="line">            &#125;)</span><br><span class="line">        &#125;)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    &#125;)</span><br><span class="line">    ctx.body=<span class="string">&quot;开始导入数据&quot;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">//导出路由</span></span><br><span class="line"><span class="built_in">module</span>.exports=router;</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//然后在启动文件里 挂在路由 index.js</span></span><br><span class="line"><span class="keyword">let</span> goods = <span class="built_in">require</span>(<span class="string">&#x27;./appApi/goods.js&#x27;</span>)</span><br><span class="line">router.use(<span class="string">&#x27;/goods&#x27;</span>,goods.routes())</span><br></pre></td></tr></table></figure>
<h2 id="分页算法"><a href="#分页算法" class="headerlink" title="分页算法"></a>分页算法</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span>首先你需要知道当前页 这和是前台给你传过来</span><br><span class="line"><span class="number">2.</span>你要知道每一页给前台传过多少条数据</span><br><span class="line"><span class="number">3.</span>你要知道从从数组的那个位置开始传</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">router.post(<span class="string">&#x27;/fenye&#x27;</span>,<span class="keyword">async</span> (ctx) =&gt; &#123;</span><br><span class="line">    <span class="keyword">let</span> page = ctx.request.body.page <span class="comment">//前台给你传过来的当前页书</span></span><br><span class="line">    <span class="keyword">let</span> num = <span class="number">10</span> <span class="comment">//你每一页给他返回十条数据</span></span><br><span class="line">    <span class="comment">//这里的意思就是 当你前台是第一页的时候 我就从数据库的第0的索引给你查 如果你是第二页 那我就从数据的索引为10的开始给你查如果你是第三页 我就送数据库索引为20的位置开始给你查</span></span><br><span class="line">    <span class="keyword">let</span> start = (page-<span class="number">1</span>) * num</span><br><span class="line">    <span class="comment">//skip就是我从索引第几的位置开始给你查  limit就是查几条</span></span><br><span class="line">    <span class="keyword">let</span> retsult = <span class="keyword">await</span> Goods.find().skip(start).limit().exec</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
</article><div class="post-copyright"><div class="post-copyright__title"><span class="post-copyright-info"><h>Koa2</h></span></div><div class="post-copyright__type"><span class="post-copyright-info"><a href="http://example.com/2019/03/25/koa/">http://example.com/2019/03/25/koa/</a></span></div><div class="post-copyright-m"><div class="post-copyright-m-info"><div class="post-copyright-a"><h>作者</h><div class="post-copyright-cc-info"><h>北城韩雨</h></div></div><div class="post-copyright-c"><h>发布于</h><div class="post-copyright-cc-info"><h>2019-03-25</h></div></div><div class="post-copyright-u"><h>更新于</h><div class="post-copyright-cc-info"><h>2019-06-03</h></div></div><div class="post-copyright-c"><h>许可协议</h><div class="post-copyright-cc-info"><a class="icon" rel="noopener" target="_blank" title="Creative Commons" href="https://creativecommons.org/"><i class="fab fa-creative-commons"></i></a><a rel="noopener" target="_blank" title="CC BY-NC-SA 4.0" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a></div></div></div></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Koa2/">Koa2</a></div><div class="post_share"></div></div><link rel="stylesheet" href="/" media="defer" onload="this.media='all'"/><div class="post-reward"><button class="tip-button reward-button"><span class="tip-button__text">打赏</span><div class="coin-wrapper"><div class="coin"><div class="coin__middle"></div><div class="coin__back"></div><div class="coin__front"></div></div></div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/img/weixin.jpg" target="_blank"><img class="post-qr-code-img" src="/img/weixin.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/img/taobao.jpg" target="_blank"><img class="post-qr-code-img" src="/img/taobao.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></button></div><script defer="defer" src="/"></script><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2019/03/25/Node/"><img class="prev-cover" src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.vjshi.com%2F2016-12-29%2F0604092c7129acd0f4029c6728db7fd7%2F00001.jpg%3Fx-oss-process%3Dstyle%2Fwatermark&amp;refer=http%3A%2F%2Fpic.vjshi.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1629530724&amp;t=333c5056a813a542419e5b661ebcfcd9" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">NodeJs</div></div></a></div><div class="next-post pull-right"><a href="/2019/03/24/%E7%A7%BB%E5%8A%A8%E7%AB%AF%E7%BE%8E%E9%A3%9FwebAPP-react/"><img class="next-cover" src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fcz-video-photo.oss-cn-beijing.aliyuncs.com%2F20191017%2F4cfc341591d242327b67e9ceb6953612_00002.jpg&amp;refer=http%3A%2F%2Fcz-video-photo.oss-cn-beijing.aliyuncs.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1629530702&amp;t=80943e12d5239f63beafd6d1c540855f" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">webAPP 美食项目</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2019/03/26/koa与mongoose/" title="Koa与mongoose"><img class="cover" src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.vjshi.com%2F2018-07-17%2F3eca5394963b50e37b7be2ba320029ec%2F00003.jpg%3Fx-oss-process%3Dstyle%2Fwatermark&refer=http%3A%2F%2Fpic.vjshi.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1629530644&t=10679b5732c52e39eeb588040240a790" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2019-03-26</div><div class="title">Koa与mongoose</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/img/my.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">北城韩雨</div><div class="author-info__description">一个前端界的小学生</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">65</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">23</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">21</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/wazer1987"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="/wangzhengvslike@163.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content"><p>感谢访问本站，如喜欢请收藏。本站主要分享前端知识，立志成为资深前端工程师，但目前是一个前端界的小学生 若喜欢可以打赏请博主喝一杯冰阔落</p> <p>另外请大家多多支持淼哥的开源项目</p> <p>https://github.com/flipped-aurora/gin-vue-admin</p> <p>🌟🌟欢迎大家start 🌟🌟</p> <p>欢迎加入博主的前端技术交流群</p> <p style="background:rgba(255,255,255,1);margin:0"> <img src="/img/code.png"></img> </p></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#koa%E6%AD%A3%E5%B8%B8%E6%B5%81%E7%A8%8B"><span class="toc-text">koa正常流程</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%8A%E4%BC%A0%E6%96%87%E4%BB%B6"><span class="toc-text">上传文件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%90%8E%E7%AB%AF%E6%8E%A5%E6%94%B6%E6%96%87%E4%BB%B6-%E4%B8%89%E7%A7%8D%E6%96%B9%E5%BC%8F"><span class="toc-text">后端接收文件 三种方式</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#koa-router%E7%9A%84%E9%85%8D%E7%BD%AE"><span class="toc-text">koa-router的配置</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#koa-bodyParser"><span class="toc-text">koa-bodyParser</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%AE%BE%E7%BD%AE%E8%B7%A8%E5%9F%9F-cors"><span class="toc-text">设置跨域 cors</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#mongoose%E9%93%BE%E6%8E%A5"><span class="toc-text">mongoose链接</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E5%BB%BA%E7%AB%8B%E9%93%BE%E6%8E%A5"><span class="toc-text">1.建立链接</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E8%B0%83%E7%94%A8%E9%93%BE%E6%8E%A5"><span class="toc-text">2.调用链接</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-%E5%AF%86%E7%A0%81%E7%9A%84%E5%8A%A0%E5%AF%86%E5%A4%84%E7%90%86"><span class="toc-text">3.密码的加密处理</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B3%A8%E5%86%8C%E7%9A%84%E4%BB%A3%E7%A0%81"><span class="toc-text">注册的代码</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%99%BB%E5%BD%95"><span class="toc-text">登录</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%95%B0%E6%8D%AE%E5%BA%93%E6%96%87%E4%BB%B6%E7%9A%84%E5%86%99%E5%85%A5"><span class="toc-text">数据库文件的写入</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%86%E9%A1%B5%E7%AE%97%E6%B3%95"><span class="toc-text">分页算法</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2021/04/16/gin-vue-admin/" title="Gin-Vue-Admin"><img src="/img/gin-vue-admin.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Gin-Vue-Admin"/></a><div class="content"><a class="title" href="/2021/04/16/gin-vue-admin/" title="Gin-Vue-Admin">Gin-Vue-Admin</a><time datetime="2021-04-15T16:00:00.000Z" title="发表于 2021-04-16 00:00:00">2021-04-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/01/08/Vue%E6%BA%90%E7%A0%81%E5%BC%80%E5%8F%91%E4%B9%8B%E7%BB%84%E4%BB%B6%E7%9A%84%E6%B8%B2%E6%9F%9310/" title="Vue源码开发-组件的渲染10"><img src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.vjshi.com%2F2018-07-17%2F3eca5394963b50e37b7be2ba320029ec%2F00003.jpg%3Fx-oss-process%3Dstyle%2Fwatermark&amp;refer=http%3A%2F%2Fpic.vjshi.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1629530644&amp;t=10679b5732c52e39eeb588040240a790" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Vue源码开发-组件的渲染10"/></a><div class="content"><a class="title" href="/2021/01/08/Vue%E6%BA%90%E7%A0%81%E5%BC%80%E5%8F%91%E4%B9%8B%E7%BB%84%E4%BB%B6%E7%9A%84%E6%B8%B2%E6%9F%9310/" title="Vue源码开发-组件的渲染10">Vue源码开发-组件的渲染10</a><time datetime="2021-01-07T16:00:00.000Z" title="发表于 2021-01-08 00:00:00">2021-01-08</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/01/07/Vue%E6%BA%90%E7%A0%81%E5%BC%80%E5%8F%91%E4%B9%8B%E7%BB%84%E4%BB%B6%E7%9A%84%E5%90%88%E5%B9%B6%E7%AD%96%E7%95%A509/" title="Vue源码开发-组件合并策略09"><img src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fcz-video-photo.oss-cn-beijing.aliyuncs.com%2F20191017%2F4cfc341591d242327b67e9ceb6953612_00002.jpg&amp;refer=http%3A%2F%2Fcz-video-photo.oss-cn-beijing.aliyuncs.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1629530702&amp;t=80943e12d5239f63beafd6d1c540855f" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Vue源码开发-组件合并策略09"/></a><div class="content"><a class="title" href="/2021/01/07/Vue%E6%BA%90%E7%A0%81%E5%BC%80%E5%8F%91%E4%B9%8B%E7%BB%84%E4%BB%B6%E7%9A%84%E5%90%88%E5%B9%B6%E7%AD%96%E7%95%A509/" title="Vue源码开发-组件合并策略09">Vue源码开发-组件合并策略09</a><time datetime="2021-01-06T16:00:00.000Z" title="发表于 2021-01-07 00:00:00">2021-01-07</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/01/06/Vue%E6%BA%90%E7%A0%81%E5%BC%80%E5%8F%91%E4%B9%8B%E6%95%B0%E7%BB%84%E7%9A%84%E4%BE%9D%E8%B5%96%E6%94%B6%E9%9B%8608/" title="Vue源码开发-数组的依赖收集08"><img src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.vjshi.com%2F2018-07-17%2F3eca5394963b50e37b7be2ba320029ec%2F00003.jpg%3Fx-oss-process%3Dstyle%2Fwatermark&amp;refer=http%3A%2F%2Fpic.vjshi.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1629530644&amp;t=10679b5732c52e39eeb588040240a790" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Vue源码开发-数组的依赖收集08"/></a><div class="content"><a class="title" href="/2021/01/06/Vue%E6%BA%90%E7%A0%81%E5%BC%80%E5%8F%91%E4%B9%8B%E6%95%B0%E7%BB%84%E7%9A%84%E4%BE%9D%E8%B5%96%E6%94%B6%E9%9B%8608/" title="Vue源码开发-数组的依赖收集08">Vue源码开发-数组的依赖收集08</a><time datetime="2021-01-05T16:00:00.000Z" title="发表于 2021-01-06 00:00:00">2021-01-06</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/01/06/Vue%E6%BA%90%E7%A0%81%E5%BC%80%E5%8F%91%E4%B9%8B%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E5%90%88%E5%B9%B607/" title="Vue源码开发-生命周期合并07"><img src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.vjshi.com%2F2018-07-17%2Faf41dabad727ba80c9ca8a2bfbd22a58%2F00004.jpg%3Fx-oss-process%3Dstyle%2Fwatermark&amp;refer=http%3A%2F%2Fpic.vjshi.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1629530659&amp;t=bbcfe1e86f393eecbb0722db1b92e475" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Vue源码开发-生命周期合并07"/></a><div class="content"><a class="title" href="/2021/01/06/Vue%E6%BA%90%E7%A0%81%E5%BC%80%E5%8F%91%E4%B9%8B%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E5%90%88%E5%B9%B607/" title="Vue源码开发-生命周期合并07">Vue源码开发-生命周期合并07</a><time datetime="2021-01-05T16:00:00.000Z" title="发表于 2021-01-06 00:00:00">2021-01-06</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright"><span>&copy;2017 - 2021</span><svg style="width:2em; height:2em;position: relative;top: 10px;" aria-hidden="true"><use xlink:href="#icon-Butterfly"></use></svg><span>北城韩雨</span></div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><p><a style="margin-inline:5px" target="_blank" href="https://hexo.io/"><img src="https://img.shields.io/badge/Frame-Hexo-blue?style=flat&logo=hexo" title="博客框架为Hexo"></a><a style="margin-inline:5px" target="_blank" href="https://butterfly.js.org/"><img src="https://img.shields.io/badge/Theme-Butterfly-6513df?style=flat&logo=bitdefender" title="主题采用butterfly"></a><a style="margin-inline:5px" target="_blank" href="https://www.jsdelivr.com/"><img src="https://img.shields.io/badge/CDN-jsDelivr-orange?style=flat&logo=jsDelivr" title="本站使用JsDelivr为静态资源提供CDN加速"></a></p></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/medium-zoom/dist/medium-zoom.min.js"></script><div class="js-pjax"></div><script defer src="/live2d-widget/autoload.js"></script><script src="/js/coin.js"></script><script async src="//at.alicdn.com/t/font_2700632_3rtvhzzpl3h.js"></script><script src="/js/liuxing.js" data-pjax></script><canvas class="fireworks" mobile="false"></canvas><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/fireworks.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = true;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><!-- hexo injector body_end start --><div class="js-pjax"><script async="async">var arr = document.getElementsByClassName('recent-post-item');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__zoomIn');
    arr[i].setAttribute('data-wow-duration', '1s');
    arr[i].setAttribute('data-wow-delay', '0ms');
    arr[i].setAttribute('data-wow-offset', '100');
    arr[i].setAttribute('data-wow-iteration', '1');
  }</script><script async="async">var arr = document.getElementsByClassName('card-widget');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__zoomIn');
    arr[i].setAttribute('data-wow-duration', '');
    arr[i].setAttribute('data-wow-delay', '');
    arr[i].setAttribute('data-wow-offset', '');
    arr[i].setAttribute('data-wow-iteration', '');
  }</script></div><script defer src="https://cdn.jsdelivr.net/gh/graingert/wow@1.3.0/dist/wow.min.js"></script><script defer src="https://cdn.jsdelivr.net/npm/hexo-butterfly-wowjs/lib/wow_init.min.js"></script><script async src="//at.alicdn.com/t/font_2032782_8d5kxvn09md.js"></script><!-- hexo injector body_end end --></body></html>